/*
 * @Description:
 * @Author: qingyang
 * @Date: 2023-02-23 20:18:29
 * @LastEditors: qingyang
 * @LastEditTime: 2023-03-07 17:19:17
 */
import { ref, Ref, computed, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { queryBaseInfo } from '@/apis/eci/inventory/inventory';
import { InventoryStatusEnum } from '@/constants/enum';
import { isString } from '@/utils/is';
import {useMessage} from '@/hooks/useMessage'
const hasChange = ref(false);

export const useSteps = () => {
  const planNoRes = ref(''); // 接口返回的planNo
  const baseRef = ref();
  const emissionRef = ref();
  const goNextLoading = ref(false);
  const commitLoading = ref(false);
  const route = useRoute();
  const router = useRouter();
  const currentStatus = ref('BASE'); //当前状态
  const isReadOnly = ref(false);
  const isCopyEdit = ref(false); // 是否是复制的监测计划编辑
  const { createMessage } = useMessage();
  const isEdit = computed(() => {
    const { inventoryNo } = route.query;
    return !!inventoryNo;
  });
  const headerTitle = computed(() => {
    return isReadOnly.value
      ? formData.inventoryName
      : isEdit.value
      ? '编辑监测计划'
      : '创建监测计划';
  });
  const formData = reactive<any>({
    inventoryNo: '',
    inventoryName: '',
    organizationCode: '',
    organizationName: '',
    applicableYear: '',
    companyName: '',
    companyAddress: '',
    contact: '',
    contactEmail: '',
    contactPhone: '',
    boundary: '',
    planarFileList: [],
    fillFrequency: '',
    auditorId: '',
    auditor: '',
    auditorEmail: '',
    auditorExist: undefined
  });
  const id = computed(() => {
    const { inventoryNo } = route.query;
    return (inventoryNo as string) || planNoRes.value;
  });
  const onCancel = () => {
    router.go(-1);
  };
  const goNext = () => {
    // 只读 直接跳过到下一步
    if (isReadOnly.value) {
      currentStatus.value = 'EMISSION';
      return;
    }
    checkHandler(baseRef);
  };
  const checkHandler = (checkRef: Ref) => {
    if(!formData.auditorExist) {
      createMessage.error((`审核人【${formData.auditor}】不存在，请重新选择其他审核人！`));
      return 
    }
    checkRef.value
      ?.check()
      .then((res: string) => {
        console.log('checkHandler success', res);
        planNoRes.value = isString(res) ? res : '';
        currentStatus.value = 'EMISSION';
      })
      .catch((error: any) => {
        console.log('checkHandler error', error);
      })
      .finally(() => {
        goNextLoading.value = false;
      });
  };
  const goPrevious = () => {
    currentStatus.value = 'BASE';
  };
  const goCommit = () => {
    emissionRef.value?.check().then(() => {
      router.replace('/emissionInventory');
    });
  };

  /**
   * 加载数据
   */
  async function loadData() {
    try {
      const data = await queryBaseInfo(id.value);
      isReadOnly.value = data.status == InventoryStatusEnum.RELEASED;
      if (data.auditorExist === false) {
        formData.auditorId = data.auditor;
      } else {
        formData.auditorId = data.auditorId;
      }
      formData.auditor = data.auditor;
      formData.auditorEmail = data.auditorEmail;
      formData.auditorExist = data.auditorExist;
      formData.inventoryNo = data.inventoryNo;
      formData.inventoryName = data.inventoryName;
      formData.organizationCode = data.organizationCode;
      formData.organizationName = data.organizationName;
      formData.applicableYear = data.applicableYear;
      isCopyEdit.value = !data.applicableYear;
      formData.companyName = data.companyName;
      formData.companyAddress = data.companyAddress;
      formData.contact = data.contact;
      formData.contactEmail = data.contactEmail;
      formData.contactPhone = data.contactPhone;
      formData.boundary = data.boundary;
      formData.planarFileList = data.planarGraphUrl
        ? [{ name: data.planarGraphName, url: data.planarGraphUrl }]
        : [];
      formData.fillFrequency = data.fillFrequency;
    } catch (error) {
      console.log('error', error);
    }
  }

  /**
   * 更新审核人id
   */
  function updateAuditId(auditorId: string) {
    formData.auditorId = auditorId;
  }

  onMounted(async () => {
    // 如果存在id 则加载详情
    if (id.value) {
      loadData();
    }
  });

  return {
    headerTitle,
    id,
    currentStatus,
    formData,
    onCancel,
    goPrevious,
    goNext,
    goCommit,
    isReadOnly,
    goNextLoading,
    commitLoading,
    baseRef,
    emissionRef,
    isCopyEdit,
    updateAuditId
  };
};
export const useChangeData = () => {
  const changeHandle = () => {
    hasChange.value = true;
  };
  onMounted(() => {
    hasChange.value = false;
  });
  return {
    hasChange,
    changeHandle
  };
};
